import 'package:flutter/material.dart';

import '../utils/api.dart';

class UserProvider extends ChangeNotifier {
  String? nickname;
  String? avatarUrl;
  int? id;
  int? gender;
  String? phone;

  bool loading = false;

  // 新增字段，保持状态，默认0或空
  String? ipLocation;
  int followingCount = 0;
  int followersCount = 0;
  int likeCount = 0;
  int favoriteCount = 0;
  bool isFollowing = false;

  Future<void> fetchUserInfo(String userId) async {
    loading = true;
    notifyListeners();

    try {
      final res = await Api.get('/user/$userId');
      // 假设接口返回结构是 { code: 0, data: {...}, msg: '' }
      if (res['code'] == 0) {
        final data = res['data'];
        nickname = data['nickname'];
        avatarUrl = data['avatar'];
        phone = data['phone'];
        gender = data['gender'];
        id = data['id'];

        // 这里填充新增字段，接口中必须包含这些字段或null检查
        ipLocation = data['ipLocation'] ?? '';
        followingCount = data['followingCount'] ?? 0;
        followersCount = data['followersCount'] ?? 0;
        likeCount = data['likeCount'] ?? 0;
        favoriteCount = data['favoriteCount'] ?? 0;
        isFollowing = data['isFollowing'] ?? false;
      } else {
        throw Exception('接口错误：${res['msg']}');
      }
    } catch (e) {
      print('fetchUserInfo error: $e');
    } finally {
      loading = false;
      notifyListeners();
    }
  }

  Future<void> updateNickname(String newName, String id) async {
    try {
      final res = await Api.postForm(
        '/user/updateNickname',
        params: {'id': id, 'nickName': newName},
      );
      if (res['code'] == 0) {
        nickname = newName;
        notifyListeners();
      } else {
        throw Exception('更新昵称失败：${res['msg']}');
      }
    } catch (e) {
      print('updateNickname error: $e');
    }
  }

  Future<void> updateGender(int sex, String userId) async {
    try {
      final res = await Api.postForm(
        '/user/updateGender',
        params: {'id': userId, 'gender': sex.toString()},
      );

      if (res['code'] == 0) {
        gender = sex;
        notifyListeners();
      } else {
        throw Exception('更新性别失败：${res['msg']}');
      }
    } catch (e) {
      print('updateGender error: $e');
    }
  }

  Future<void> updateAvatar(String newAvatarUrl, String id) async {
    try {
      final res = await Api.postForm(
        '/user/updateAvatar',
        params: {'id': id, 'avatar': newAvatarUrl},
      );
      if (res['code'] == 0) {
        avatarUrl = newAvatarUrl;
        notifyListeners();
      } else {
        throw Exception('更新头像失败：${res['msg']}');
      }
    } catch (e) {
      print('updateAvatar error: $e');
    }
  }
}
